<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>内容抓取与AI润色系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            color: white;
            margin-bottom: 40px;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
        }

        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }

        .card {
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.15);
            margin-bottom: 20px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            margin-bottom: 8px;
            color: #333;
        }

        .form-group textarea,
        .form-group input,
        .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .form-group textarea:focus,
        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }

        .form-group textarea {
            min-height: 150px;
            resize: vertical;
            font-family: 'Courier New', monospace;
        }

        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .checkbox-group input {
            width: auto;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 14px 32px;
            font-size: 16px;
            font-weight: 600;
            border-radius: 8px;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            width: 100%;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
        }

        .btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }

        .progress-section {
            display: none;
        }

        .progress-section.active {
            display: block;
        }

        .progress-bar-container {
            background: #f0f0f0;
            border-radius: 10px;
            height: 30px;
            overflow: hidden;
            margin-bottom: 15px;
        }

        .progress-bar {
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
            height: 100%;
            width: 0%;
            transition: width 0.5s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
        }

        .current-status {
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 15px;
        }

        .current-status p {
            margin: 5px 0;
            color: #555;
        }

        .results-grid {
            display: grid;
            gap: 15px;
            margin-top: 20px;
        }

        .result-item {
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }

        .result-item.success {
            border-left-color: #28a745;
        }

        .result-item.failed {
            border-left-color: #dc3545;
        }

        .result-item .url {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
            word-break: break-all;
        }

        .result-item .details {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
        }

        .result-item .actions {
            display: flex;
            gap: 10px;
        }

        .download-btn {
            padding: 6px 12px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
            text-decoration: none;
            display: inline-block;
        }

        .download-btn:hover {
            background: #5568d3;
        }

        .error-message {
            color: #dc3545;
            font-size: 14px;
            margin-top: 5px;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
            margin-left: 10px;
        }

        .status-badge.pending {
            background: #ffc107;
            color: #000;
        }

        .status-badge.processing {
            background: #17a2b8;
            color: white;
        }

        .status-badge.completed {
            background: #28a745;
            color: white;
        }

        .status-badge.failed {
            background: #dc3545;
            color: white;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }

        .stat-card .number {
            font-size: 2em;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .stat-card .label {
            font-size: 0.9em;
            opacity: 0.9;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 3px solid rgba(255,255,255,.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s linear infinite;
            margin-right: 8px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 内容抓取与AI润色系统</h1>
            <p>批量抓取网页内容并使用AI进行智能润色</p>
        </div>

        <div class="card">
            <form id="processForm">
                <div class="form-group">
                    <label for="urls">📝 输入URL列表（每行一个）</label>
                    <textarea 
                        id="urls" 
                        placeholder="https://example.com/article1&#10;https://example.com/article2&#10;https://example.com/article3"
                        required
                    ></textarea>
                </div>

                <div class="form-group">
                    <label for="task">🎯 处理任务</label>
                    <input 
                        type="text" 
                        id="task" 
                        value="润色和优化"
                        placeholder="例如：润色和优化、总结要点、翻译为中文"
                    >
                </div>

                <div class="form-group">
                    <label for="aiProvider">🤖 AI提供商</label>
                    <select id="aiProvider">
                        <option value="deepseek">DeepSeek</option>
                        <option value="openai">OpenAI</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="customPrompt">📋 自定义提示词（可选）</label>
                    <textarea 
                        id="customPrompt" 
                        placeholder="使用 {content} 作为内容占位符&#10;&#10;示例：请将以下内容翻译为中文并优化表达：&#10;{content}"
                        style="min-height: 100px;"
                    >你是一名专业的文案编辑师。
                    然后需要针对下面的博客文案进行优化撰写产出，一篇公众号长文。
                    可以采用风格1进行撰写修改文案。
                    输出的格式需要是markdown源码格式,即带有符号如#号表示一级标题之类的，方便复制。
                    请将以下英文翻译为中文，要求语言优美自然，适合中文语境表达，可以适度意译，避免生硬直译。
                    风格1:英文精准翻译为中文，保持技术术语或专有名词的一致性，不要省略或添加内容，只需忠实还原原意。
                    原始内容：
                    {content}
                </textarea>
                </div>

                <div class="form-group checkbox-group">
                    <input type="checkbox" id="saveOriginal" checked>
                    <label for="saveOriginal" style="margin-bottom: 0;">💾 同时保存原始内容</label>
                </div>

                <button type="submit" class="btn" id="submitBtn">
                    开始处理
                </button>
            </form>
        </div>

        <div class="card progress-section" id="progressSection">
            <h2>处理进度 <span class="status-badge" id="statusBadge">pending</span></h2>
            
            <div class="progress-bar-container">
                <div class="progress-bar" id="progressBar">0%</div>
            </div>

            <div class="current-status" id="currentStatus">
                <p><strong>当前状态：</strong><span id="statusText">初始化中...</span></p>
                <p><strong>当前URL：</strong><span id="currentUrl">-</span></p>
            </div>

            <div class="stats">
                <div class="stat-card">
                    <div class="number" id="totalCount">0</div>
                    <div class="label">总任务数</div>
                </div>
                <div class="stat-card">
                    <div class="number" id="completedCount">0</div>
                    <div class="label">已完成</div>
                </div>
                <div class="stat-card">
                    <div class="number" id="successCount">0</div>
                    <div class="label">成功</div>
                </div>
                <div class="stat-card">
                    <div class="number" id="failedCount">0</div>
                    <div class="label">失败</div>
                </div>
            </div>

            <div class="results-grid" id="resultsGrid"></div>
        </div>
    </div>

    <script>
        // const API_BASE = 'http://localhost:8080/api';
        const API_BASE = 'http://47.121.216.193:8081/api';  // 修改为相对路径

        let currentTaskId = null;
        let pollInterval = null;

        document.getElementById('processForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const urlsText = document.getElementById('urls').value.trim();
            const urls = urlsText.split('\n').filter(url => url.trim());
            
            if (urls.length === 0) {
                alert('请至少输入一个URL');
                return;
            }

            const requestData = {
                urls: urls,
                task: document.getElementById('task').value,
                ai_provider: document.getElementById('aiProvider').value,
                custom_prompt: document.getElementById('customPrompt').value || null,
                save_original: document.getElementById('saveOriginal').checked
            };

            const submitBtn = document.getElementById('submitBtn');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner"></span>提交中...';

            try {
                const response = await fetch(`${API_BASE}/process`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(requestData)
                });

                const data = await response.json();
                
                if (response.ok) {
                    currentTaskId = data.task_id;
                    document.getElementById('progressSection').classList.add('active');
                    startPolling();
                } else {
                    alert('提交失败：' + (data.detail || '未知错误'));
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '开始处理';
                }
            } catch (error) {
                alert('网络错误：' + error.message);
                submitBtn.disabled = false;
                submitBtn.innerHTML = '开始处理';
            }
        });

        function startPolling() {
            if (pollInterval) clearInterval(pollInterval);
            
            pollInterval = setInterval(async () => {
                if (!currentTaskId) return;

                try {
                    const response = await fetch(`${API_BASE}/task/${currentTaskId}`);
                    const task = await response.json();
                    
                    updateProgress(task);

                    if (task.status === 'completed' || task.status === 'failed') {
                        clearInterval(pollInterval);
                        document.getElementById('submitBtn').disabled = false;
                        document.getElementById('submitBtn').innerHTML = '开始处理';
                    }
                } catch (error) {
                    console.error('轮询错误:', error);
                }
            }, 1000);
        }

        function updateProgress(task) {
            const progress = task.total > 0 ? (task.completed / task.total * 100) : 0;
            
            document.getElementById('progressBar').style.width = progress + '%';
            document.getElementById('progressBar').textContent = Math.round(progress) + '%';
            
            const statusBadge = document.getElementById('statusBadge');
            statusBadge.textContent = task.status;
            statusBadge.className = `status-badge ${task.status}`;
            
            document.getElementById('statusText').textContent = getStatusText(task.status);
            document.getElementById('currentUrl').textContent = task.current_url || '无';
            
            document.getElementById('totalCount').textContent = task.total;
            document.getElementById('completedCount').textContent = task.completed;
            
            const successCount = task.results.filter(r => r.success).length;
            const failedCount = task.results.filter(r => !r.success).length;
            
            document.getElementById('successCount').textContent = successCount;
            document.getElementById('failedCount').textContent = failedCount;
            
            renderResults(task.results);
        }

        function getStatusText(status) {
            const statusMap = {
                'pending': '等待开始...',
                'processing': '正在处理...',
                'completed': '处理完成！',
                'failed': '处理失败'
            };
            return statusMap[status] || status;
        }

        function renderResults(results) {
            const grid = document.getElementById('resultsGrid');
            grid.innerHTML = results.map(result => {
                const statusClass = result.success ? 'success' : 'failed';
                const icon = result.success ? '✅' : '❌';
                
                let html = `
                    <div class="result-item ${statusClass}">
                        <div class="url">${icon} ${result.url}</div>
                `;
                
                if (result.success) {
                    html += `
                        <div class="details">
                            📊 原始长度: ${result.original_length} 字符
                            | 润色后: ${result.polished_length} 字符
                        </div>
                        <div class="actions">
                            <a href="${API_BASE}/download/${currentTaskId}/${result.polished_file}" 
                               class="download-btn" target="_blank">
                                📥 下载润色版
                            </a>
                            ${result.original_file ? `
                                <a href="${API_BASE}/download/${currentTaskId}/${result.original_file}" 
                                   class="download-btn" target="_blank">
                                    📄 下载原始版
                                </a>
                            ` : ''}
                        </div>
                    `;
                } else {
                    html += `
                        <div class="error-message">错误: ${result.error}</div>
                    `;
                }
                
                html += '</div>';
                return html;
            }).join('');
        }
    </script>
</body>
</html>